var express = require('express');
var router = express.Router();
var multer  = require('multer');
var path =require('path');

//设置对象
var storage = multer.diskStorage({  
	destination: function (req, file, cb) {
	  cb(null, './uploads')
	},
	filename: function (req, file, cb) {
	  cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
	}
  })

router.post('/upload',function(req,res,next){
	var upload=multer({
		storage: storage,
		fileFilter:function(req,file,callback){
			
			var ext =path.extname(file.originalname);
			if(ext!=='.png' && ext!=='.jpg' && ext!=='.gif' && ext!=='.jpeg'){
				return callback(res.end('文件类型不符合'));
			}
			callback(null,true);
		}
	}).single('avatar')
	upload(req,res,function(err){
		console.log(req.file);
		res.json(req.file);
		//res.end('file uploaded');
		
	})
	
})

/* GET home page. */
router.get('/', function(req, res, next) {
	res.render('index', { title: 'Express' });
});

module.exports = router;
